package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayAddressDto;
import org.itboys.mobile.service.mongo.front.SundayFrontAddressService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zhangyang
 * 时间：2017年12月18日
 * 描述：圣代_收货地址_controller_mobile
 */
@Controller
@RequestMapping("/sunday/mobile/address")
public class SundayMobileAddressController extends BaseController {
    @Autowired
    private SundayFrontAddressService addressService;


    /**
     * 查询用户收货地址
     * @param
     */
    @RequestMapping(value="/select", method={ RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】查询用户收货地址。")
    public void select(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayAddressDto> result =addressService.select(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }


    /**
     * 保存新增或更新用户地址
     * @param request
     * @param response
     * @param id
     * @param receiveName
     * @param receiveMobile
     * @param receiveAddress
     */
    @RequestMapping(value="/save", method= RequestMethod.POST)
    @ApiOperation(value="【手机端】保存新增或更新用户地址")
    public void save(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="id", value="地址id。新增时传入0。【参与签名】")@RequestParam(value = "id", required = true)Long id,
            @ApiParam(required=true, name="receiveName", value="收货人姓名。")@RequestParam(value = "receiveName", required = true)String receiveName,
            @ApiParam(required=true, name="receiveMobile", value="手机号码。")@RequestParam(value = "receiveMobile", required = true)String receiveMobile,
            @ApiParam(required=false, name="provinceId", value="省ID。")@RequestParam(value = "provinceId", required = false)Long provinceId,
            @ApiParam(required=false, name="provinceName", value="省名称。")@RequestParam(value = "provinceName", required = false)String provinceName,
            @ApiParam(required=false, name="cityId", value="市ID。")@RequestParam(value = "cityId", required = false)Long cityId,
            @ApiParam(required=false, name="cityName", value="市名称。")@RequestParam(value = "cityName", required = false)String cityName,
            @ApiParam(required=false, name="districtId", value="区县ID。")@RequestParam(value = "districtId", required = false)Long districtId,
            @ApiParam(required=false, name="districtName", value="区县名称。")@RequestParam(value = "districtName", required = false)String districtName,
            @ApiParam(required=true, name="receiveAddress", value="详细地址。")@RequestParam(value = "receiveAddress", required = true)String receiveAddress,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("id",id);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.save(id,memberId,receiveName,receiveMobile,provinceId,provinceName,cityId,cityName,districtId,districtName,receiveAddress);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 设置默认地址
     * @param request
     * @param response
     * @param addressId
     */
    @RequestMapping(value="/setDefault", method=RequestMethod.POST)
    @ApiOperation(value="【手机端】设置当前地址为默认地址")
    public void setDefault(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="addressId", value="地址id。【参与签名】")@RequestParam(value = "addressId", required = true)Long addressId,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("addressId",addressId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.setDefault(addressId, memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/setDefault----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 单个删除收货地址
     * @param request
     * @param response
     * @param addressId
     */
    @RequestMapping(value="/delete", method=RequestMethod.POST)
    @ApiOperation(value="【手机端】删除地址")
    public void delete(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required=true, name="addressId", value="地址id。【参与签名】")@RequestParam(value = "addressId", required = true)Long addressId,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月17日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("addressId",addressId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            addressService.delete(addressId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/address/delete----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
